package com.itheima.interceptors;

import com.itheima.mapper.UserMapper;
import com.itheima.pojo.Result;
import com.itheima.pojo.User;
import com.itheima.utils.JwtUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.Map;

@Component
public class LoginInterceptor implements HandlerInterceptor {
    public static final ThreadLocal<User> curUser = new ThreadLocal<>();

    @Autowired
    private UserMapper userMapper;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) {

        System.out.println(request.getRequestURL() + "被拦截了");
        System.out.println(request.getRequestURL() + "被拦截了");

        String token = request.getHeader("Authorization");
        try {
            Map<String, Object> stringObjectMap = JwtUtil.parseToken(token);
            String username = (String)stringObjectMap.get("username");
            User currentUser = userMapper.findByUserName(username);
            curUser.set(currentUser);
            return true;
        } catch (Exception e) {
            response.setStatus(401);
            return false;
        }
    }
}
